/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.spa.modules.gen.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spa.common.api.vo.Result;
import com.spa.common.generate.EosCodeFactory;
import com.spa.common.generate.config.DataSourceConfig;
import com.spa.common.generate.config.EosGlobalConfig;
import com.spa.common.generate.config.converts.MySqlTypeConvert;
import com.spa.common.generate.po.TableField;
import com.spa.common.generate.utils.CommonUtils;
import com.spa.modules.gen.entity.GenData;
import com.spa.modules.gen.entity.GenTable;
import com.spa.modules.gen.entity.GenTableColumn;
import com.spa.modules.gen.mapper.GenDataBaseDictMapper;
import com.spa.modules.gen.mapper.GenDataMapper;
import com.spa.modules.gen.mapper.GenTableMapper;

import cn.hutool.core.util.StrUtil;
/**
 * 业务表Service
 * 
 * @author ThinkGem
 * @version 2013-10-15
 */
@Service
@Transactional(readOnly = true)
public class GenTableService extends ServiceImpl<GenTableMapper, GenTable> {

    @Autowired
    private GenTableMapper genTableMapper;
    
    @Autowired
	private GenDataMapper genDataMapper;
    
    @Autowired
    private GenDataBaseDictMapper genDataBaseDictMapper;

    /**
     * 分页列表查询
     *
     * @param spaUser
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Result<Object> queryPageList(HttpServletRequest req, Integer pageNo, Integer pageSize) {
        Page<GenTable> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<GenTable> queryWrapper = new LambdaQueryWrapper<>();
        Page<GenTable> articlePage = genTableMapper.selectPage(page, queryWrapper);
        List<GenTable> records = articlePage.getRecords();
        return Result.resultOK(records);
    }

    /**
     * 添加
     *
     * @param testTabel
     * @return
     */
    @Transactional
    public Result<Object> insert(GenTable genTable) {
        genTableMapper.insert(genTable);
        return Result.resultOK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param spaUser
     * @return
     */
    @Transactional
    public Result<Object> saveById(GenTable genTable) {
        genTableMapper.updateById(genTable);
        return Result.resultOK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Transactional
    public Result<Object> deleteById(String id) {
        genTableMapper.deleteById(id);
        return Result.resultOK("删除成功!");
    }

    /**
     * 生成代码
     *
     * @param id
     * @return
     * @throws Exception 
     */
    public Result<Object> createtfl(GenTable genTable) throws Exception {
    	
    	genTable = genTableMapper.selectById(genTable.getId());
    	
    	// 全局配置
        EosGlobalConfig globalConfig = new EosGlobalConfig();
        // 自定义模板路径
        globalConfig.setTemplatepath(genTable.getTemplateName());
        globalConfig.setIntroduce(genTable.getComments());
        globalConfig.setAuthor(genTable.getFunctionAuthor());
        globalConfig.setEntity(genTable.getClassName());
        globalConfig.setItem(StrUtil.lowerFirst(genTable.getClassName()));
        // 文件输出路径，不配置的话默认输出当前项目的resources/code目录下
        globalConfig.setOutputDir(genTable.getOutputDir());
        globalConfig.setPackagePath(genTable.getPackageName());
        
        GenData genData = genDataMapper.selectById(genTable.getDbId());

        
        // 数据库配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDriverName(genData.getDrive());
        dsc.setUrl(genData.getDbUrl());
        // 填写自己的数据库账号
        dsc.setUsername(genData.getDbUsername());
        // //填写自己的数据库密码
        dsc.setPassword(genData.getDbPassword());

        // 代码生成方法
        try {
            EosCodeFactory codeFactory = new EosCodeFactory(globalConfig, dsc);
            codeFactory.generateFile("controller");
            codeFactory.generateFile("service");
            codeFactory.generateFile("entity");
            codeFactory.generateFile("dao");
           // codeFactory.generateFile("view");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return Result.resultOK("生成代码成功!");
    }
    
    /**
	 * 根据表名获取该表的所有字段
	 * 
	 * @param tableName 表名称
	 * @return
	 */
	private List<TableField> getTbfrFields(String tableName) {
		List<GenTableColumn> genTableColumnList = genDataBaseDictMapper.findTableColumnList(tableName);
		List<TableField> tbColumns = new ArrayList<TableField>();
		for(GenTableColumn genTableColumn:genTableColumnList) {
			TableField tbfrField = new TableField();
			String fieldNm = genTableColumn.getName().toLowerCase();
			tbfrField.setName(fieldNm);// 表字段名
			tbfrField.setPropertyName(CommonUtils.getNoUnderlineStr(fieldNm));// 字段名
			tbfrField.setComment(genTableColumn.getComments());// 字段注释
			tbfrField.setType(genTableColumn.getJdbcType());// 字段类型
			tbfrField.setColumnType(new MySqlTypeConvert().processTypeConvert(genTableColumn.getJdbcType()));

			if (fieldNm.equals("id")) {
				tbfrField.setKeyIdentityFlag(true);
			} else {
				tbfrField.setKeyIdentityFlag(false);
			}
			tbColumns.add(tbfrField);
		}
		return tbColumns;

	}

}
